<?php
namespace App\Traits;

use DB;
trait DbTrait
{

    public function checkSmsExistTrait($data)
    {
        $whereData = [
            'phone' => $data['phone'],
            'code' => $data['code'],
            'from' => $data['from'],
        ];
        $result = DB::table('sms_code_log')
            ->where($whereData)
            ->where('create_time', '>', time() - 1800)
            ->first();
        return isset($result->id) ? true : false;
    }

    public function dbAddSmsCodeLog($data)
    {
        $time = time();
        $secondCount = DB::table('sms_code_log')
            ->where('phone', $data['phone'])
            ->where('create_time', '>', $time - 60)
            ->where('from', $data['from'])
            ->count();
        if ($secondCount != 0) {
            return ['result' => -1, 'msg' => '60秒时间未到'];
        }
        $phoneCount = DB::table('sms_code_log')
            ->where('phone', $data['phone'])
            ->where('create_time', '>', $time - 600)
            ->where('from', $data['from'])
            ->count();
        if ($phoneCount > 3) {
            return ['result' => -1, 'msg' => '10分钟之内只能获取3次'];
        }
        $ipCount = DB::table('sms_code_log')
            ->where('phone', $data['phone'])
            ->where('create_time', '>', $time - 60)
            ->where('from', $data['from'])
            ->where('ip', $data['ip'])
            ->count();
        if ($ipCount != 0) {
            return ['result' => -1, 'msg' => '每个IP60秒之内只能获取一次'];
        }
        $insertData = [
            'phone' => $data['phone'],
            'code' => $data['code'],
            'type' => $data['type'],
            'create_time' => $time,
            'from' => $data['from'],
            'ip' => $data['ip'],
        ];
        DB::table('sms_code_log')->insert($insertData);
        return ['result' => 0, 'msg' => '验证码发送成功'];
    }

    public function validateEmailFlag($data)
    {
        $result = DB::table('email_validate_info')
            ->where('md5', $data['md5'])
            ->where('email', $data['email'])
            ->where('isValidate', 0)
            ->where('expire_time', '>', time())
            ->first();
        return $result ? json_decode(json_encode($result), true) : false;
    }

    public function validateEmailFlagSuccess($data)
    {
        $updateData = [
            'isValidate' => 1,
            'validate_time' => date('Y-m-d H:i:s', time()),
        ];
        DB::table('email_validate_info')
            ->where('id', $data['id'])
            ->update($updateData);
        return true;
    }

    public function addEmailValidateInfo($data)
    {
        $data['expire_time'] = time() + 3600;
        DB::table('email_validate_info')
            ->insert($data);
    }
}
